package com.jt.tenant.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.jt.tenant.R;
import com.jt.tenant.app.JTApplication;
import com.jt.tenant.conn.GetJuHe;
import com.jt.tenant.conn.SetCarDetail;
import com.jt.tenant.dialog.EditDialog;
import com.jt.tenant.dialog.MyTimePopup;
import com.jt.tenant.fragment.CarFragment;
import com.jt.tenant.fragment.HomeFragment;
import com.jt.tenant.widget.Tools;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.util.UtilToast;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by yzf on 2016/2/4.
 */
public class CarInfoActivity extends JTActivity implements View.OnClickListener {

    private TextView title_name,commit,select;

    //品牌、车型、排量、年款、变速挡
    private EditText tv_pp, tv_category_name, tv_pl, tv_nk, tv_bsx;

    private EditText et_enginecode, et_plate_num;

    private TextView et_gmnf;

    private TextView et_vincode;

    private LinearLayout lin_buy_year;

    //车架号、发动机号、购买年份、车牌号
    private String car_plate_num, car_vincode, car_enginecode, car_gmnf;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;

    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;

    public AMapLocationListener mLocationListener = null;

    private String vin = "";

    public static RefreshLinster refreshLinster;

    private String pp = "",pl = "",nk = "",cx = "",bsx = "";

    private MyTimePopup timePopupWindow;

    private String BRAND,CS,CM,DM,TM,YEAR;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_car_info);

        init_view();

    }



    private void init_view() {

        (title_name = (TextView) findViewById(R.id.tv_title_name)).setText("车辆信息");

        (commit = (TextView) findViewById(R.id.commit)).setOnClickListener(this);

        (select = (TextView)findViewById(R.id.tv_car_info_select)).setOnClickListener(this);

        if(JTApplication.jtPreferences.readBSX().equals("null") || JTApplication.jtPreferences.readBSX() == null){

            (tv_bsx = (EditText) findViewById(R.id.car_info_tv_bsx)).setText("");

        }else{

            (tv_bsx = (EditText) findViewById(R.id.car_info_tv_bsx)).setText(JTApplication.jtPreferences.readBSX());

        }

        if(JTApplication.jtPreferences.readCX().equals("null") || JTApplication.jtPreferences.readCX() == null){

            (tv_category_name = (EditText) findViewById(R.id.car_info_tv_categoryName)).setText("");

        }else{

            (tv_category_name = (EditText) findViewById(R.id.car_info_tv_categoryName)).setText(JTApplication.jtPreferences.readCX());

        }


        if(JTApplication.jtPreferences.readPP().equals("null") || JTApplication.jtPreferences.readPP() == null){

            (tv_pp = (EditText) findViewById(R.id.car_info_tv_pp)).setText("");

        }else{

            (tv_pp = (EditText) findViewById(R.id.car_info_tv_pp)).setText(JTApplication.jtPreferences.readPP());

        }

        if(JTApplication.jtPreferences.readNK().equals("null") || JTApplication.jtPreferences.readNK() == null){

            (tv_nk = (EditText) findViewById(R.id.car_info_tv_nk)).setText("");

        }else{

            (tv_nk = (EditText) findViewById(R.id.car_info_tv_nk)).setText(JTApplication.jtPreferences.readNK());

        }



        if (JTApplication.jtPreferences.readPL().equals("null") || JTApplication.jtPreferences.readPL() == null) {

            (tv_pl = (EditText) findViewById(R.id.car_info_tv_pl)).setText("");

        } else {

            (tv_pl = (EditText) findViewById(R.id.car_info_tv_pl)).setText(JTApplication.jtPreferences.readPL());

        }

        (et_enginecode = (EditText) findViewById(R.id.car_info_et_engineCode)).setText(JTApplication.jtPreferences.readEngineCode());

        (et_gmnf = (TextView) findViewById(R.id.car_info_et_gmnf)).setText(JTApplication.jtPreferences.readRemark());

        (et_plate_num = (EditText) findViewById(R.id.car_info_et_plateNums)).setText(JTApplication.jtPreferences.readPlateNum());

        (et_vincode = (TextView) findViewById(R.id.car_info_et_vincode)).setText(JTApplication.jtPreferences.readVincode());

        lin_buy_year = (LinearLayout)findViewById(R.id.lin_buy_year);



        timePopupWindow = new MyTimePopup(context, null, new Date(), MyTimePopup.Type.YEAR_MONTH_DAY) {

            private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");

            @Override
            public void onSubmit(Date date) {

                et_gmnf.setText(simpleDateFormat.format(date));

            }

        };

        et_vincode.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                EditDialog dialog = new EditDialog(CarInfoActivity.this);

                dialog.show();

            }
        });

        lin_buy_year.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                //先关闭软键盘
                View view = getWindow().peekDecorView();

                if (view != null) {

                    InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

                    inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);

                }

                timePopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);

            }
        });

        if (JTApplication.jtPreferences.readVincode().equals("")) {

            UtilToast.show(context, "请先输入车架号，以便查询车辆信息");

        }

        refreshLinster = new RefreshLinster() {

            @Override
            public void refresh(String vincode) {

                et_vincode.setText(vincode);

                vin = et_vincode.getText().toString().trim();

                //聚合请求获得车辆信息
                new GetJuHe(vin, new AsyCallBack<GetJuHe.Info>() {

                    @Override
                    public void onSuccess(String toast, int type, GetJuHe.Info info) throws Exception {

                        UtilToast.show(context, "聚合数据请求成功");

                        JTApplication.jtPreferences.saveVincode(info.VIN);

                        String a = info.CARINFO;

                        String b[] = a.split(" ");

                        for (int i = 0; i < b.length; i++) {

                            tv_pp.setText(b[0]);

                            pp = b[0];

                            JTApplication.jtPreferences.savePP(b[0]);

                            tv_category_name.setText(b[1]);

                            cx = b[1];

                            JTApplication.jtPreferences.saveCX(b[1]);

                            tv_nk.setText(b[3]);

                            nk = b[3];

                            JTApplication.jtPreferences.saveNK(b[3]);

                            tv_pl.setText(b[4] + "L");

                            pl = b[4];

                            JTApplication.jtPreferences.savePL(b[4]);

                            tv_bsx.setText(b[5]);

                            bsx = b[5];

                            JTApplication.jtPreferences.saveBSX(b[5]);

                            JTApplication.jtPreferences.savePZ(b[6]);

                        }

                    }

                    @Override
                    public void onFail(String toast, int type) throws Exception {

                        super.onFail(toast, type);

                        UtilToast.show(context, "聚合数据请求失败，请手动输入车辆信息");

                    }

                }).execute(context);

            }
        };

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            //提交车辆信息
            case R.id.commit:

                car_gmnf = et_gmnf.getText().toString();

                car_enginecode = et_enginecode.getText().toString();

                car_vincode = et_vincode.getText().toString();

                car_plate_num = et_plate_num.getText().toString();

                pp = tv_pp.getText().toString().trim();

                cx = tv_category_name.getText().toString().trim();

                nk = tv_nk.getText().toString().trim();

                bsx = tv_bsx.getText().toString().trim();

                pl = tv_pl.getText().toString().trim();

                if(pp.equals("")||cx.equals("")||nk.equals("")||pl.equals("")||bsx.equals("")){

                    UtilToast.show(context,"请输入车辆信息");

                }else if (car_gmnf.equals("")) {

                    UtilToast.show(this, "购买年份不能为空");

                } else if (car_enginecode.equals("")) {

                    UtilToast.show(this, "发动机号不能为空");

                } else if (car_vincode.equals("")|| !Tools.isVinNO(car_vincode)) {

                    UtilToast.show(this, "请输入正确车架号");

                } else if (car_plate_num.equals("")||!Tools.isPlateNO(car_plate_num)) {

                    UtilToast.show(this, "请输入正确车牌号");

                } else {

                    commit_carinfo();

                }

                break;

            case R.id.tv_car_info_select:

                startActivityForResult(new Intent(CarInfoActivity.this, ChooseModelsActivity.class),11);

                break;



        }

    }

    /**
     * 请求接口
     */
    private void commit_carinfo() {

        new SetCarDetail(car_plate_num, car_vincode, car_enginecode, car_gmnf,pp,pl,nk,cx,bsx, new AsyCallBack<SetCarDetail.Info>() {

            @Override
            public void onSuccess(String toast, int type, SetCarDetail.Info info) throws Exception {

                super.onSuccess(toast, type, info);

                if (info.msg.equals("000")) {

                    if (JTApplication.jtPreferences.readAccountState().equals("0")){

                        JTApplication.jtPreferences.saveAccountState("1");

                        if(HomeFragment.refreshLinstener != null) {

                            HomeFragment.refreshLinstener.refresh();

                        }

                    }

                    UtilToast.show(CarInfoActivity.this, "车辆设置完成");

                    //将信息保存起来
                    //机动车号
                    JTApplication.jtPreferences.saveEngineCode(car_enginecode);

                    //车牌号
                    JTApplication.jtPreferences.savePlateNum(car_plate_num);

                    //车架号
                    JTApplication.jtPreferences.saveVincode(car_vincode);

                    JTApplication.jtPreferences.savePL(pl);

                    JTApplication.jtPreferences.savePP(pp);

                    JTApplication.jtPreferences.saveNK(nk);

                    JTApplication.jtPreferences.saveCX(cx);

                    JTApplication.jtPreferences.saveBSX(bsx);

                    JTApplication.jtPreferences.saveRemark(car_gmnf);

                    if(CarFragment.refreshLinster != null){

                        CarFragment.refreshLinster.refresh();

                    }

                    finish();

                } else {

                    UtilToast.show(CarInfoActivity.this, info.msg);

                }

            }

            @Override
            public void onFail(String toast, int type) throws Exception {

                super.onFail(toast, type);

                UtilToast.show(CarInfoActivity.this, toast);

            }

        }).execute(this);

    }

    public abstract class RefreshLinster {

        public abstract void refresh(String vincode);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
            case RESULT_OK:

                Bundle b=data.getExtras(); //data为B中回传的Intent

                BRAND = b.getString("BRAND");

                CS = b.getString("CS");

                CM = b.getString("CM");

                DM = b.getString("DM");

                TM = b.getString("TM");

                YEAR = b.getString("YEAR");

                tv_pp.setText(BRAND);

                tv_category_name.setText(CS+"  "+CM);

                tv_pl.setText(DM);

                tv_bsx.setText(TM);

                tv_nk.setText(YEAR);

                break;
            default:
                break;
        }

    }
}
